<template>
  <div id="testlistpanel">
    <el-row class='imgPreview'>
    <vxe-toolbar class-name="bg-orange light pandList">
      <template #buttons>
        <span class="padding-lr-xs">
          <vxe-button
            type="text"
            content="截取"
            class-name="padding-lr-xs"
            class="button-blue padding-lr-xs"
            @click="begainScreen()"
          />
        </span>
        <span class="padding-lr-xs">
          <el-upload
            class="upload-demo"
            :data="paramData"
            :headers="headers"
            :action="uploadFilePath"
            :show-file-list="false"
            multiple
            :on-success="onSuccess"
            :on-error="onError"

          >
<!--            :disabled="uploadDisabled"-->
<!--              :disabled="uploadDisabled"-->
            <vxe-button
              type="text"
              content="上传"
              class-name="padding-lr-xs"
              class="button-blue padding-lr-xs"
              @click="upload()"
            />
          </el-upload>
        </span>
      </template>
    </vxe-toolbar>
    <div class="demo-image__lazy">
      <div class='el-image' style='background-color: #8a919498'>
        <canvas  id="canvasItem"
                 style="width: calc(100% - 2px); height: calc(100% - 166px);z-index:999;"
                 v-show='false'></canvas>
        <video ref="videoEl" id="videoItem" style="
          width: calc(100% - 2px);
          height: calc(100% - 166px);z-index:999999;" />
      </div>
    </div>
    </el-row>
    <div style="height: 160px;overflow-x: auto;width:calc(100% - 2px);">
      <div
        class="main-img"
        ref="mainImg"
        v-loading="loading"
        style="height:calc(100% - 40px);overflow-x: auto;width:calc(100% - 2px);"
      >
        <ul class="img-box">
          <li
            v-for="(item, index) in wLFileList"
            :key="index"
            :style="{
              width: imgWidth + 'px',
              height: imgHeight + 'px',
            }"
          >
            <el-image :src="picUrlBase + item.imageUrl"
                      :initial-index="index"></el-image>
            <el-checkbox
                         :checked ='item.isChecked==="1"'
                         @change="val => selectFile(val, item)"
                         v-if='resultIsDisabled()'>
            </el-checkbox>
            <el-button type="danger" :icon="Delete" circle @click="deleteImg(item)"
            v-if='resultIsDisabled()'
            />
          </li>
        </ul>
      </div>
    </div>
  </div>
  <ScreenShot v-if="screenshotStatus"
                @destroy-component="destroyComponent"
                @get-image-data="getImg"
  ></ScreenShot>
</template>
<script setup lang="ts">
import { reactive,
  ref,
  getCurrentInstance,
  onMounted,
  onBeforeUnmount,
  inject,defineExpose,
  defineEmits} from 'vue';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { UploadProps } from 'element-plus';
import {Delete} from '@element-plus/icons-vue'
import VXETable from 'vxe-table';
import 'vxe-table/lib/style.css';
import { IsEmpty } from '@/utils/common';
import DictChildList from '@/views/system_set/DictChildList.vue';
let images: any = reactive([]); //图片信息集合
let isChk = ref(0); //是否审核
let disabled = ref(true);
let uploadDisabled = ref(true);
let deleteDisabled = ref(true);
let picUrlBase = (window as any).apiUrl.VITE_SERVER_URL;
let wLFileList = reactive([]);
let currentFileList = reactive([]); //当前选中的文件数组
let id = ''; //接收传过来的检验结果id
let imgWidth = 132;
let imgHeight = 99; //图片高度，图片宽高比需要为4:3
let loading = false;
let headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
};
let labMainInfoObj: any = reactive({}); /**检验记录当前选中对象 */
const rptImages = inject('rptImages'); /**检验记录当前选中对象 */

// 请求参数数据
const paramData = reactive({
  rptGroup:'',
  sampleda:'',
  sampleNo:'',
  id: id //检验图片id
});

//使用 ref 对象来获取 DOM 元素
const videoEl = ref<HTMLVideoElement>(null);
// 存储拍摄后的图片路径
const imageUrl = ref<string | null>(null);
const pictureUrl = ref<string>((window as any).apiUrl.VITE_SERVER_URL + '/image/');
const picture =  ref(null);

defineExpose({
  initPage
});

const proxyEmit = defineEmits(['updateTestList']);

onMounted(() => {
  getImage();
  checkCamera();
});

// 上传图片 弹框
function upload() {
  paramData.id = '';
  paramData.rptGroup=labMainInfoObj.rptGroup;
  paramData.sampleda=labMainInfoObj.sampleda;
  paramData.sampleNo=labMainInfoObj.sampleNo;
}
// 上传成功
function onSuccess(e) {
  if (e && e.status && e.status.code && e.status.code === 400) {
    VxeMessage(e.status.msg.replace('IOException: ', ''), VxeNotifyType.error);
    return;
  }
  getImage();
}
//上传失败
function onError(e) {
  console.log('失败', e);
}

async function deleteImg(item) {
  console.log(item,"item");
  handleDelete(item.id)
}

//删除
async function handleDelete(id) {
  const url = '/lab/labRptImageTemp/batchDeleteImages';
  const ids = [];
  ids.push(id);

  const data = {
    eptresultImageIds: ids
  };
  proxy.$http.post(url, data).then((res: any) => {
    if (res.status.code === 1) {
      VxeMessage('删除成功', VxeNotifyType.success);
      getImage();
    } else {
      VxeMessage('删除失败', VxeNotifyType.error);
    }
  });
}

function initPage(mainInfoRow: any) {
  Object.assign(labMainInfoObj, mainInfoRow);
  getImage();
  clearPhoto();
}

// 获取图片
function getImage() {
  disabled.value = true;
  currentFileList.length = 0;
  wLFileList.length = 0;
  const url = '/lab/labRptImageTemp/findImagesByMaininfoId';
  paramData.rptGroup=labMainInfoObj.rptGroup;
  paramData.sampleda=labMainInfoObj.sampleda;
  paramData.sampleNo=labMainInfoObj.sampleNo;
  proxy.$http
    .get(url, {
      params: {
        rptGroup:paramData.rptGroup,
        sampleda:paramData.sampleda,
        sampleNo:paramData.sampleNo
      } })
    .then(async (res: any) => {
      if (!IsEmpty(res.data) && res.data) {
        wLFileList.push(...res.data);
        wLFileList.forEach((item) => {
          if(item.isChecked==="1"){
            currentFileList.push(item);
          }
        });
        rptImages.value=currentFileList;
        if (IsEmpty(labMainInfoObj.id)) {
          //proxy.$emit
          labMainInfoObj.id=res.data.maininfoId;
          proxyEmit('updateTestList', { isSelCurRow: true, isRefreshRptResult: false, mainInfoId: res.data.maininfoId });
        }
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 选中文件
function selectFile(checked, val) {
  const index = currentFileList.findIndex((item) => {
    return item.id === val.id;
  });

  // 未勾选 且 元素在 currentFileList 中存在，删除
  if (!checked && index > -1) {
    currentFileList.splice(index, 1);
  }
  // 勾选 且 元素在 currentFileList 中没有，添加进去
  if (checked && index === -1) {
    currentFileList.push(val);
  }
  rptImages.value=currentFileList;
  if(val.isChecked==="1"){
    unSelectImagesChecked(val);
  }else {
    selectImagesChecked(val);
  }

}

function resultIsDisabled() {
  if (!IsEmpty(labMainInfoObj) && labMainInfoObj.isChk == '2') {
    return false;
  } else {
    return true;
  }
}

//选择检验图片保存到图文
async function selectImagesChecked(item) {
  const url = '/lab/labRptImageTemp/selectImagesChecked';
  proxy.$http.get(url, {
    params: {id: item.id }
  }).then((res: any) => {
    if (res.status.code === 200) {
      item.isChecked="1";
      VxeMessage('选择检验图片保存到图文成功', VxeNotifyType.success);
    } else {
      VxeMessage('选择检验图片保存到图文失败', VxeNotifyType.error);
    }
  });
}

//取消检验图片保存到图文
async function unSelectImagesChecked(item) {
  const url = '/lab/labRptImageTemp/unSelectImagesChecked';
  proxy.$http.get(url, {
    params: {id: item.id }
  }).then((res: any) => {
    console.log(res,"res");
    if (res.status.code === 200) {
      item.isChecked="0";
      VxeMessage('取消检验图片成功', VxeNotifyType.success);
    } else {
      VxeMessage('取消检验图片成功失败', VxeNotifyType.error);
    }
  });
}

// 上传图片
const uploadFilePath = ref((window as any).apiUrl.VITE_SERVER_URL + '/lab/labRptImageTemp/uploadImage');

//摄像头相关开始

const clearPhoto = () => {
  picture.value= picture.value = null;
  //获得Canvas对象
  const canvas: any = document.getElementById('canvasItem');
  if (canvas) {
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, 200, 200);
  }
};

// 拍摄函数，截取摄像头当前帧并显示在页面上
function begainScreen() {
  clearPhoto();
  // 检查视频元素和页面容器是否存在
  if (!videoEl.value) return;
  setTimeout(async () => {
    const canvas: any = document.getElementById('canvasItem');
    if (canvas) {
      canvas.width = videoEl.value.videoWidth;
      canvas.height = videoEl.value.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx?.drawImage(videoEl.value, 0, 0, canvas.width, canvas.height);
      picture.value = canvas.toDataURL('image/png');
      setTimeout(() => {
        uploadImage();
      }, 50);
    }
  }, 50);
}

// 检查摄像头并设置视频流
async function checkCamera() {
  clearPhoto();
  const navigator = window.navigator.mediaDevices;
  const devices = await navigator.enumerateDevices();
  // 如果存在媒体设备，获取摄像头视频流
  if (devices) {
    // 请求用户媒体设备（摄像头）
    const stream = await navigator.getUserMedia({
      audio: false,
      video: {
        width: videoEl.value.videoWidth, // 设置视频宽度
        height: videoEl.value.videoHeight, // 设置视频高度
        facingMode: 'user' // 使用前置摄像头
      }
    });
    // 如果视频元素存在，将视频流绑定到视频元素上并开始播放
    if (videoEl.value) {
      videoEl.value.srcObject = stream;
      videoEl.value.play();
    }
  }
}

const uploadImage = async () => {
  if (picture.value) {
    const response = await fetch(picture.value);
    const blob = await response.blob();
    let formData=new FormData();
    formData.append('id', paramData.id);
    formData.append('rptGroup', paramData.rptGroup);
    formData.append('sampleda', paramData.sampleda);
    formData.append('sampleNo', paramData.sampleNo);
    formData.append('file', blob);
    try {
      const uploadResponse =
      await fetch(uploadFilePath.value, {
        method: 'POST',
        body:formData,
        headers:headers,
      });
      console.log(uploadResponse,"uploadResponse")
      getImage();
      clearPhoto();
    } catch (error) {
      console.error('网络请求错误', error);
    }
  }
};

</script>
<style lang="scss" scoped>
#testlistpanel {
  height: 100%;
  // 附加按钮间距
  //.button-red {
  //  margin: 5px 0 0 5px;
  //}
  // 中间table表格

  .demo-image__lazy {
    float: inline-end;
    width: calc(100% - 0px);
    height: calc(100vh - 260px);
    overflow: auto;
  }
   .el-image {
    display: block;
    min-width: calc(100% - 80px);
    margin-bottom: 10px;
     overflow-x: auto;
  }
  .demo-image__lazy .el-image:last-child {
    margin-bottom: 0;
  }
  .imgPreview{
    height: calc(100vh - 260px);
  }
  .pandList{
    text-align: center;
    z-index: 999;
    position: absolute;
    background: unset;
  }
  img:hover {
    transform: scale(1.2);
  }
  :deep(.vxe-body--row) {
    height: 80px;
  }

  .el-checkbox {
    position: absolute;
    top: 5px;
    left: 6px;
  }
  .el-link {
    position: absolute;
    top: 0px;
    right: 0px;
    i {
      margin-right: -2px;
      font-size: 16px;
    }
  }
  .main-img {
    ul.img-box {
      margin: 0;
      padding: 0;
      list-style-type: none;
      overflow: auto;

      > li {
        position: relative;
        display: inline; //让li横向排列
        padding: 5px;
        float: left;
      }

      .el-image {
        width: 132px;
        height: 99px;
        border: 1px #aaa solid;
        box-sizing: border-box;
      }
      .el-checkbox {
        position: absolute;
        top: 0px;
        left: 6px;
      }
      .el-button {
        position: absolute;
        top: 0px;
        right: 0px;
      }
      .el-link {
        position: absolute;
        top: 0px;
        right: 0px;
        i {
          margin-right: -2px;
          font-size: 16px;
        }
      }
    }
  }
}
</style>
